package org.rexsong.sample.petstore.services;

import org.rexsong.sample.petstore.exceptions.CustomerExistsException;
import org.rexsong.sample.petstore.models.Customer;
import org.rexsong.sample.petstore.repositories.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerServiceImp implements CustomerService {

    private CustomerRepository customerRepository;

    @Autowired
    public CustomerServiceImp(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public Customer addCustomer(Customer customer) throws CustomerExistsException {
        if(customerRepository.findByName(customer.getName()).size() > 0) {
            throw new CustomerExistsException(String.format("Customer %s exists.", customer.getName()));
        }
        return customerRepository.save(customer);
    }

    @Override
    public List<Customer> findAll() {
        return customerRepository.findAll();
    }
}
